package com.heima.search.listen;

import com.heima.common.exception.CustException;
import com.heima.es.service.EsService;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.constants.message.NewsUpOrDownConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ArticleAddOrRemoveListener {

    @Autowired
    ArticleFeign articleFeign;

    @Autowired
    EsService<SearchArticleVO> esService;

    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void handleUp(String articleId){
        log.info("搜索微服务 接收到添加文章到索引库消息==> {}",articleId);
        // 1. 远程 查询文章信息
        ResponseResult<SearchArticleVO> articleResult = articleFeign.findArticle(Long.valueOf(articleId));
        if(!articleResult.checkCode()){
            log.error("远程查询文章信息失败==> {}",articleId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程查询文章信息失败");
        }
        SearchArticleVO searchArticleVO = articleResult.getData();
        if (searchArticleVO==null) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"未查询到相关文章");
        }
        // 2. 保存到索引库
        esService.save(searchArticleVO,"app_info_article");
        log.info("成功将新增文章 保存到索引库==> {}",articleId);
    }

    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void handleDown(String articleId){
        log.info("搜索微服务 接收到删除文章到索引库消息==> {}",articleId);
        esService.deleteById(articleId,"app_info_article");
        log.info("成功将下架文章 从索引库中删除==> {}",articleId);
    }
}
